'use strict';

const { Service } = require('egg');
const dayjs = require("dayjs");
const ModelName = 'User'
class RouterService extends Service {
    /**
     * 根据分页和搜索条件获取
     * @param {Object} where 查询用户的条件
     * @param {Number} page 当前分页
     * @param {Number} pageSize 当前页每页多少条
     */
    async getPage(where, page, pageSize) {
        return this.ctx.model[ModelName].findAndCountAll({
            where,
            offset: pageSize * (page - 1),
            limit: pageSize,
            order:[
                // id 降序
                ['created_at','DESC']
            ],
            include: [
                {
                    model: this.ctx.model.Product,
                    as: 'product'
                }
            ]
        });
    }

    // 所有列表
    async allList(where) {
        return this.ctx.model[ModelName].findAll({
            where,
            order:[
                // id 降序
                ['created_at','DESC']
            ],
        });
    }
    async findOne(id) {
        const user = await this.ctx.model[ModelName].findOne({
            where: {
                id,
            },
        });
        // 当天是否抽过奖品
        const today = dayjs().format('YYYY-MM-DD');
        const lotteryRecord = await this.ctx.model.UserPracticeRecord.findOne({
            where: {
                user_id: id,
                is_lottery: 1,
                // 时间是当天
                created_time: {
                    [this.app.Sequelize.Op.gte]: today + ' 00:00:00',
                }
            }
        })
        console.log('lotteryRecord',lotteryRecord)
        if (lotteryRecord) {
            user.setDataValue('is_day_lottery', 1);
        }
        return user
    }

    /**
     * 创建
     * @param {*} data 角色信息
     */
    async create(data) {
        // 判断账号是否存在
        const user = await this.ctx.model[ModelName].findOne({
            where: { username: data.username },
        })
        if (user) throw new Error('手机号已存在');
        await this.ctx.model[ModelName].create(data);
        return this.login(data)
    }
    async login({ phone, username, nickname }) {
        // 根据账号查询用户是否存在
        let user = await this.ctx.model[ModelName].findOne({
            where: { username },
        });
        if (!user) {
            // 自动注册
            user = await this.ctx.model[ModelName].create({ username, nickname, phone });
        }
        return user;
    }

    /**
     * 根据ID修改
     * @param {Number} id ID
     * @param {Object} data 要修改的信息
     */
    async update(id, data) {
        return await this.ctx.model[ModelName].update(data, { where: { id } });
    }

    /**
     * 根据id删除
     * @param {Number}
     */
    async deleteById(id) {
        return await this.ctx.model[ModelName].destroy({ where: { id } });
    }
}

module.exports = RouterService;
